const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require('koa2-cors')

const crawlerRouter = require('./routes/crawler')
const indexRouter = require('./routes/index')
const adminRouter = require('./routes/adminRoutes')

const session = require('koa-generic-session');
const koaRedis = require('koa-redis');

const { sessionInfo, cookieInfo, redisInfo, corsOrigin } = require('./config/config');

//配置跨域
app.use(cors({
  origin: function (ctx) {
    return corsOrigin; //配置所有3000端口的请求可以跨域访问
  },
  credentials: true //给予前端跨域携带cookie的权限
}))

//session相关
//用来加密cookie的key
app.keys = sessionInfo.keys;  

app.use(session({
    key: sessionInfo.name,		//cookie的 name
    prefix: sessionInfo.prefix,  //redis key 前缀， session存入redis时的前缀
    cookie: cookieInfo,
    store: koaRedis( redisInfo )
  }
))
//上面这些步骤给浏览器客户端带上了cookie，在控制台里可以看到


// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(crawlerRouter.routes(), crawlerRouter.allowedMethods());
app.use(indexRouter.routes(), indexRouter.allowedMethods());
app.use(adminRouter.routes(), adminRouter.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
